﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Eneta.Portal.Common;
using Eneta.Portal.Common.Dto;
using Eneta.Portal.Common.Repository;
using Eneta.Portal.Common.Services;
using Microsoft.SharePoint;

namespace Eneta.Portal.Companies.WebParts.CompanyEditWebPart
{
    public partial class CompanyEditWebPartUserControl : UserControl
    {
        private Dictionary<string, string> _errors = new Dictionary<string, string>();

        private CompanyRepository _companyRepository;

        private CompanyRepository CompanyRepository
        {
            get
            {
                if (_companyRepository != null)
                    return _companyRepository;

                _companyRepository = new CompanyRepository(EnetaApplication.PortalCompaniesSiteUrl);
                return _companyRepository;
            }
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            EnableViewState = true;

            IOLevel1Repeater.ItemDataBound += IoLevel1RepeaterItemDataBound;
            saveButton.Click += SaveButtonClick;
            errorsRepeater.ItemDataBound += ErrorsRepeaterItemDataBound;
        }

        protected void ErrorsRepeaterItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.DataItem == null)
                return;

            var label = (Label)e.Item.FindControl("errorLabel");
            label.Text = e.Item.DataItem.ToString();
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            ApplyErrors(_errors);

            if (string.IsNullOrEmpty(urlField.Text) || urlField.Text.ToLower() == "http://")
            {
                urlField.CssClass = "text-go clear";
                urlField.Text = "http://";
            }
            else
                urlField.CssClass = "text-go";

            if (string.IsNullOrEmpty(streetField.Text))
                streetField.Text = Resources.GetResourceString("StreetPlaceholder");

            if (streetField.Text == Resources.GetResourceString("StreetPlaceholder"))
                streetField.CssClass = "text-go clear";
            else
                streetField.CssClass = "text-go";

            if (string.IsNullOrEmpty(contactPhoneField.Text))
                contactPhoneField.Text = Resources.GetResourceString("PhonePlaceholder");

            if (contactPhoneField.Text == Resources.GetResourceString("PhonePlaceholder"))
                contactPhoneField.CssClass = "text-go clear";
            else
                contactPhoneField.CssClass = "text-go";

            SetCheckStyles(Controls);
        }

        private static void SetCheckStyles(ControlCollection controls)
        {
            foreach (Control c in controls)
                if (c.GetType() == typeof(CheckBox))
                    ((CheckBox)c).InputAttributes["class"] = "choice";
                else if (c.HasControls())
                    SetCheckStyles(c.Controls);

        }

        protected void SaveButtonClick(object sender, EventArgs e)
        {
            SetCompanyValidationErrors();
            if (_errors.Count > 0)
            {
                return;
            }

            var dto = new CompanyDto();
            if (Item != null)
                dto.Id = Item.Id;

            dto.Title = nameField.Text;
            dto.CertifiedEmployees = certifiedEmployeesField.Text;
            dto.City = cityField.Text;
            dto.ContactEmail = contactEmailField.Text;
            dto.ContactName = contactField.Text;
            dto.ContactPhone = contactPhoneField.Text;
            dto.Description = descriptionField.Text;
            dto.Employees = employeesList.SelectedValue;
            dto.HomePage = urlField.Text;

            dto.Offices.Clear();
            dto.Offices.AddRange(GetOffices());

            dto.PartnershipLevel = partnershipLevel.SelectedValue;
            dto.Street = streetField.Text;
            dto.Zip = zipField.Text;

            var topics = GetSelectedTopics();
            dto.IOTopics.Clear();

            foreach (var topic in topics)
                dto.IOTopics.Add(topic);

            CompanyRepository.SaveCompany(dto);

            if (logoUpload.HasFile)
                CompanyRepository.SaveCompanyLogo(dto.Id, logoUpload.FileBytes);

            var currentUser = SPContext.Current.Web.CurrentUser;

            try
            {
                if (string.IsNullOrEmpty(Request.QueryString["ID"]))
                {
                    var userMail = currentUser.Email;
                    var mailer = new MailerService();
                    var addresses = new[] { userMail, "abi@eneta.ee" };
                    mailer.SendMailByTemplate("CompanyAdded", currentUser.Name, nameField.Text, null, addresses);
                }
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
            }

            var profileRep = new UserProfileRepository(SPContext.Current.Web.Site.RootWeb);
            var profileItem = profileRep.GetUserProfileByUserName(EnetaApplication.PortalUserNamePrefix + SPContext.Current.Web.CurrentUser.LoginName);
            if (string.IsNullOrEmpty(Request.QueryString["companyID"]))
                Response.Redirect(EnetaApplication.PortalProfilePageUrl + "?profileID=" + profileItem.Id + "&msg=compadd", true);
            else
                Response.Redirect(EnetaApplication.PortalProfilePageUrl + "?profileID=" + profileItem.Id + "&msg=compsave", true);
        }

        private List<OfficeDto> GetOffices()
        {
            var offices = new List<OfficeDto>();

            foreach (ListItem item in officesList.SelectedItems())
            {
                var office = new OfficeDto();
                office.Id = int.Parse(item.Value);
                office.Title = item.Text;

                offices.Add(office);
            }

            return offices;
        }

        protected void SaveButtonClick2(object sender, EventArgs e)
        {
            var codeLoc = string.Empty;
            var pageName = string.Empty;
            var currentUser = SPContext.Current.Web.CurrentUser;
            var isNew = false;
            var id = 0;
            var selectedTopics = GetSelectedTopics();
            var wasAccepted = false;

            if (Item != null)
                if (Item.Status == SPModerationStatusType.Approved)
                    wasAccepted = true;





            if (_errors.Count > 0)
            {
                Logger.LogInfo("Error collection is not empty");
                return;
            }

            if (contactPhoneField.Text == Resources.GetResourceString("PhonePlaceholder"))
                contactPhoneField.Text = string.Empty;
            if (urlField.Text == "http://")
                urlField.Text = string.Empty;

            var siteId = SPContext.Current.Site.ID;
            var webId = SPContext.Current.Web.ID;
            var redir = string.Empty;
            var oldName = string.Empty;

            var userId = SPContext.Current.Web.CurrentUser.LoginName;
            try
            {

                var site = SPContext.Current.Site;
                var web = SPContext.Current.Web;


                if (logoUpload.HasFile)
                {
                    try
                    {
                        var img = System.Drawing.Image.FromStream(logoUpload.FileContent);
                        img.Dispose();
                    }
                    catch (Exception)
                    {
                        _errors.Add("logo", Resources.GetResourceString("LogoLoadingFailed"));
                        ApplyErrors(_errors);
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                Response.Write(new Exception("CodeLoc: " + codeLoc, ex).ToString());
                Response.End();
            }

            HttpContext.Current.Application["IoRelationsTable"] = null;

            if (string.IsNullOrEmpty(Request.QueryString["ID"]))
            {
                var userMail = currentUser.Email;
                var mailer = new MailerService();
                var addresses = new[] { userMail, "abi@eneta.ee" };
                mailer.SendMailByTemplate("CompanyAdded", currentUser.Name, nameField.Text, null, addresses);
            }

            var profileRep = new UserProfileRepository(SPContext.Current.Web.Site.RootWeb);
            var profileItem = profileRep.GetUserProfileByUserName(SPContext.Current.Web.CurrentUser.LoginName);
            if (string.IsNullOrEmpty(Request.QueryString["companyID"]))
                Response.Redirect(EnetaApplication.PortalProfilePageUrl + "?profileID=" + profileItem.Id + "&msg=compadd", true);
            else
                Response.Redirect(EnetaApplication.PortalProfilePageUrl + "?profileID=" + profileItem.Id + "&msg=compsave", true);
        }

        private void SetCompanyValidationErrors()
        {
            if (string.IsNullOrEmpty(nameField.Text))
            {
                _errors.Add("name", Resources.GetResourceString("CompanyNameRequired"));
            }
            else if (nameField.Text.Length < 4)
            {
                _errors.Add("name", Resources.GetResourceString("CompanyNameTooShort"));
            }
            else if (Item == null && CompanyRepository.CompanyExists(nameField.Text))
            {
                _errors.Add("name", Resources.GetResourceString("CompanyAlreadyExists"));
            }
            else if (nameField.Text.Length > 50)
            {
                _errors.Add("name", Resources.GetResourceString("CompanyNameTooLong"));
            }
            if (string.IsNullOrEmpty(descriptionField.Text))
            {
                _errors.Add("description", Resources.GetResourceString("DescriptionRequired"));
            }
            if (string.IsNullOrEmpty(streetField.Text) || streetField.Text == Resources.GetResourceString("StreetPlaceholder"))
            {
                _errors.Add("street", Resources.GetResourceString("AddressRequired"));
            }
            else if (streetField.Text.Length > 255)
            {
                _errors.Add("street", Resources.GetResourceString("AddressTooLong"));
            }

            if (string.IsNullOrEmpty(zipField.Text))
            {
                _errors.Add("zip", Resources.GetResourceString("ZipRequired"));
            }
            else if (zipField.Text.Length > 15)
            {
                _errors.Add("zip", Resources.GetResourceString("ZipTooLong"));
            }

            if (string.IsNullOrEmpty(cityField.Text))
            {
                _errors.Add("city", Resources.GetResourceString("CityRequired"));
            }
            else if (cityField.Text.Length > 255)
            {
                _errors.Add("city", Resources.GetResourceString("CityTooLong"));
            }

            if (officesList.SelectedItems().Count == 0)
            {
                _errors.Add("offices", Resources.GetResourceString("SelectOfficeLocation"));
            }

            if (string.IsNullOrEmpty(urlField.Text) || urlField.Text == "http://")
            {
                _errors.Add("url", Resources.GetResourceString("HomePageMissing"));
            }
            else if (urlField.Text.Length > 255)
            {
                _errors.Add("url", Resources.GetResourceString("HomePageTooLong"));
            }

            int cert;
            if (string.IsNullOrEmpty(certifiedEmployeesField.Text))
            {
                certifiedEmployeesField.Text = "0";
            }
            if (!int.TryParse(certifiedEmployeesField.Text, out cert))
            {
                _errors.Add("cert", Resources.GetResourceString("CertifiedEmployeesHasIncorrectFormat"));
            }
            else
            {
                cert = int.Parse(certifiedEmployeesField.Text);
                if (cert < 0)
                    _errors.Add("cert", Resources.GetResourceString("CertifiedEmployeesTooSmall"));
                else if (cert > 1000)
                    _errors.Add("cert", Resources.GetResourceString("CertifiedEmployeesTooBig"));
            }

            if (contactField.Text.Length > 50)
            {
                _errors.Add("contact", Resources.GetResourceString("ContactNameTooLong"));
            }

            if (contactEmailField.Text.Length > 100)
            {
                _errors.Add("contactEmail", Resources.GetResourceString("ContactEmailTooLong"));
            }

            if (contactPhoneField.Text.Length > 50)
            {
                _errors.Add("contantPhone", Resources.GetResourceString("ContactPhoneTooLong"));
            }

            var selectedTopics = GetSelectedTopics();
            if (selectedTopics.Count == 0)
            {
                _errors.Add("io", Resources.GetResourceString("SelectCompetency"));
            }

            if (!CompanyRepository.CompanyLayoutExists())
                _errors.Add("layout", Resources.GetResourceString("CompanyLayoutNotFound"));

            if (logoUpload.HasFile)
            {
                try
                {
                    var img = System.Drawing.Image.FromStream(logoUpload.FileContent);
                    img.Dispose();
                }
                catch (Exception)
                {
                    _errors.Add("logo", "Firma logofaili laadimine ebaõnnestus. Palun kontrolli, et logofail oleks korrektne.");
                }
            }
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            var currentUser = SPContext.Current.Web.CurrentUser;
            if (currentUser == null)
            {
                Response.Redirect("/");
                return;
            }

            if (Item != null)
            {
                if (string.IsNullOrEmpty(Item.AuthorUserName))
                {
                    Response.Redirect("/");
                    return;
                }

                if (Item.AuthorUserName != currentUser.LoginName)
                    if (!currentUser.IsSiteAdmin)
                    {
                        Response.Redirect("/");
                        return;
                    }
            }

            warningBox.Style["display"] = "none";

            var keys = new string[] { "name", "description", "street", "zip", "city", "offices", "url", "cert", "contact", "contactEmail", "contactName" };
            foreach (var fieldKey in keys)
            {
                var ctl = (HtmlGenericControl)this.FindControl(fieldKey + "Container", true);
                if (ctl == null)
                {
                    //Response.Write("Ei leia konteinerit: " + fieldKey + "Container<br>");
                    continue;
                    //Response.End();
                }
                ctl.Attributes.Add("class", "info-row");
                ctl = (HtmlGenericControl)this.FindControl(fieldKey + "ErrorMessage", true);
                if (ctl == null)
                {
                    //Response.Write("Ei leia konteinerit: " + fieldKey + "ErrorMessage<br>");
                    //Response.End();
                }
                else
                    ctl.Style["display"] = "none";

                ctl = (HtmlGenericControl)this.FindControl(fieldKey + "ErrorLabel", true);
                if (ctl != null)
                    ctl.InnerText = string.Empty;
            }

            if (IsPostBack)
                return;

            try
            {
                if (Request.UrlReferrer != null)
                {
                    if (fromUrlField == null)
                        Logger.LogWarning("OnLoad(): Cannot find fromUrlField");
                    else
                        fromUrlField.Value = Request.UrlReferrer.ToString();

                    if (cancelLink == null)
                        Logger.LogWarning("OnLoad(): Cannot find cancelLink");
                    else
                        cancelLink.HRef = Request.UrlReferrer.ToString();
                }
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
            }

            Bind();
        }

        private void Bind()
        {
            try
            {
                var employees = CompanyRepository.GetEmployees();
                foreach (var choice in employees)
                {
                    var listItem = new ListItem(choice, choice);
                    employeesList.Items.Add(listItem);
                }

                var partnershipLevels = CompanyRepository.GetPartnershipLevels();
                foreach (var level in partnershipLevels)
                {
                    var listItem = new ListItem(level, level);
                    partnershipLevel.Items.Add(listItem);
                }

                SPList countiesList;

                try
                {
                    countiesList = SPContext.Current.Site.RootWeb.Lists["Regions"];
                }
                catch
                {
                    countiesList = SPContext.Current.Site.RootWeb.Lists["Maakond"];
                }

                var query = new SPQuery();
                query.Query = "<OrderBy><FieldRef Name='Title' Ascending='True' /></OrderBy>";
                var counties = countiesList.GetItems(query);
                officesList.DataSource = counties;
                officesList.DataBind();

                if (Item == null)
                {
                    logoExample.Visible = false;
                    logoExample.Style["display"] = "none";
                    BindIo();
                    //TODO: Miks see null on
                    //titleLabel.Text = Resources.Companies.NewCompany;
                    certifiedEmployeesField.Text = "0";
                    return;
                }

                //TODO: Pealkirjaga tuleb midagi ette võtta
                //titleLabel.Text = Item.Title;
                nameField.Text = Item.Title;
                //fileNameLabel.Text = Item.File.Name;

                var logoName = Item.FileName.Replace(".aspx", ".png");
                var logoUrl = "/SiteCollectionImages/companies/" + logoName;
                var logoFile = SPContext.Current.Site.RootWeb.GetFile(logoUrl);
                if (!logoFile.Exists)
                {
                    logoExample.Visible = false;
                    logoExample.Style["display"] = "none";
                }
                else
                {
                    logoExample.Style["display"] = "";
                    logoExample.Src = logoUrl;
                    logoExample.Visible = true;
                }

                descriptionField.Text = Item.Description;
                streetField.Text = Item.Street;
                zipField.Text = Item.Zip;
                cityField.Text = Item.City;
                urlField.Text = Item.HomePage;

                if (employeesList.Items.FindByValue(Item.Employees) != null)
                    employeesList.SelectedValue = Item.Employees;

                if (!string.IsNullOrEmpty(Item.CertifiedEmployees))
                    certifiedEmployeesField.Text = Item.CertifiedEmployees;
                else
                    certifiedEmployeesField.Text = "0";

                contactField.Text = Item.ContactName;
                contactEmailField.Text = Item.ContactEmail;
                contactPhoneField.Text = Item.ContactPhone;

                if (Item.Offices != null)
                {
                    Logger.LogInfo("Bind(): Item.Offices count: " + Item.Offices.Count);
                    foreach (var office in Item.Offices)
                        foreach (ListItem officeItem in officesList.Items)
                            if (officeItem.Value == office.Id.ToString())
                                officeItem.Selected = true;
                }
                else
                {
                    Logger.LogInfo("Bind(): Item.Offices is null");
                }

                if (partnershipLevel.Items.FindByValue(Item.PartnershipLevel) != null)
                    partnershipLevel.SelectedValue = Item.PartnershipLevel;
            }
            catch (Exception ex)
            {
                Response.Write(ex);
                Logger.LogInfo("Bind(): Exception occured");
                Logger.LogException(ex);
            }
            BindIo();
        }

        private void BindIo()
        {
            var repository = new CompanyRepository(EnetaApplication.PortalCompaniesSiteUrl);

            try
            {
                var levels = repository.GetIoLevels();

                if (IOLevel1Repeater == null)
                {
                    Logger.LogInfo("BindIo(): Can't find IOLevel1Repeater");
                    return;
                }
                IOLevel1Repeater.DataSource = levels;
                IOLevel1Repeater.DataBind();
            }
            catch (Exception ex)
            {
                Logger.LogWarning("BindIo(): Exception occured");
                Logger.LogException(ex);
            }
        }

        protected void IoLevel1RepeaterItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.DataItem == null)
                return;

            var item = (IoLevel1)e.Item.DataItem;

            var label = (Label)e.Item.FindControl("IOLevel1Label");
            label.Text = item.Title;

            try
            {
                var repeater = (Repeater)e.Item.FindControl("IOLevel2Repeater");
                repeater.ItemDataBound += IoLevel2RepeaterItemDataBound;
                repeater.DataSource = item.Level2Items;
                repeater.DataBind();
            }
            catch (Exception ex)
            {
                Logger.LogWarning("IoLevel1RepeaterItemDataBound: Error occured");
                Logger.LogException(ex);
            }
        }

        protected void IoLevel2RepeaterItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.DataItem == null)
                return;

            var item = (IoLevel2)e.Item.DataItem;

            try
            {
                var repeater = (Repeater)e.Item.FindControl("IOTopicRepeater");
                repeater.ItemDataBound += IoTopicRepeaterItemDataBound;
                repeater.DataSource = item.Level3Items;
                repeater.DataBind();
            }
            catch (Exception ex)
            {
                Response.Write(ex.ToString());
                Response.End();
            }
        }

        protected void IoTopicRepeaterItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.DataItem == null)
                return;

            var siteId = SPContext.Current.Site.ID;
            var webId = SPContext.Current.Web.ID;

            var sec = new SPSecurity.CodeToRunElevated(delegate
            {
                using (var site = new SPSite(siteId))
                {
                    using (var web = site.AllWebs[webId])
                    {
                        var item = (IoLevel3)e.Item.DataItem;

                        var tooltipLink = (HtmlAnchor)e.Item.FindControl("tooltipLink");
                        tooltipLink.HRef = "/_layouts/enetahandlers/iotooltiphandler.ashx?l3=" + item.Id + "&width=216";

                        var label = (Label)e.Item.FindControl("IOTopicLabel");
                        label.Text = item.Title;

                        var check = (CheckBox)e.Item.FindControl("IOTopicCheckBox");
                        check.InputAttributes.Add("value", item.Id.ToString());
                        check.InputAttributes.Add("style", "width:20px");

                        if (Item != null)
                            foreach (var topic in Item.IOTopics)
                            {
                                if (topic.Id == item.Id)
                                {
                                    check.Checked = true;
                                    break;
                                }
                            }

                        var reqProductsLabel = (Label)e.Item.FindControl("RequiredProductsLabel");
                        var repeater = (Repeater)e.Item.FindControl("RequiredProductsRepeater");

                        if (item.Products.Count == 0)
                            reqProductsLabel.Text = Resources.GetResourceString("NoRequiredProducts");
                        else
                            reqProductsLabel.Text = Resources.GetResourceString("RequiredProductsLabel");
                        repeater.ItemDataBound += ProductsRepeaterItemDataBound;
                        repeater.DataSource = item.Products;
                        repeater.DataBind();
                    }
                }
            });
            SPSecurity.RunWithElevatedPrivileges(sec);
        }

        protected void ProductsRepeaterItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.DataItem == null)
                return;

            var product = (IoProduct)e.Item.DataItem;
            var label = (Label)e.Item.FindControl("ProductLabel");
            var link = (HtmlAnchor)e.Item.FindControl("ProductLink");

            label.Visible = false;
            link.Visible = false;

            if (!string.IsNullOrEmpty(product.Url))
            {
                link.HRef = product.Url;
                link.InnerText = product.Title;
                link.Visible = true;
            }
            else
            {
                label.Visible = true;
                label.Text = product.Title;
            }
        }

        private CompanyDto _item;

        private CompanyDto Item
        {
            get
            {
                if (_item != null)
                    return _item;

                var idString = Request.QueryString["companyID"];
                if (string.IsNullOrEmpty(idString))
                    return null;

                int id;
                if (!int.TryParse(idString, out id))
                    return null;

                var rep = new CompanyRepository(EnetaApplication.PortalCompaniesSiteUrl);
                _item = rep.GetCompanyById(id);

                return _item;
            }
        }

        private void ApplyErrors(Dictionary<string, string> errors)
        {
            var unboundErrors = new List<string>();

            if (errors.Count == 0)
                return;

            foreach (string fieldKey in errors.Keys)
            {
                var error = errors[fieldKey];
                var ctl = (HtmlGenericControl)this.FindControl(fieldKey + "Container", true);
                if (ctl == null)
                {
                    unboundErrors.Add(error);
                    continue;
                    //Response.End();
                }
                ctl.Attributes.Add("class", "info-row failed-info");
                ctl = (HtmlGenericControl)this.FindControl(fieldKey + "ErrorMessage", true);
                if (ctl == null)
                {
                    //Response.Write("Ei leia konteinerit: " + fieldKey + "ErrorMessage<br>");
                    //Response.End();
                }
                else
                    ctl.Style["display"] = "";

                ctl = (HtmlGenericControl)this.FindControl(fieldKey + "ErrorLabel", true);
                if (ctl == null)
                {
                    //Response.Write("Ei leia konteinerit: " + fieldKey + "ErrorLabel<br>");
                    //Response.End();
                }
                else
                    ctl.InnerText = error;
            }
            foreach (var err in unboundErrors)
                Logger.LogInfo("ApplyErrors: Unbound error: " + err);
            errorsRepeater.DataSource = unboundErrors;
            errorsRepeater.DataBind();
            Logger.LogInfo("ApplyErrors: Display");
            Logger.LogInfo("EnableViewState: " + EnableViewState);
            warningBox.Style["display"] = "";
            ViewState["Errors"] = errors;
        }

        /*private void InsertTopic(SPWeb web, int topicId)
        {
            var list = web.Lists["IOCompany"];
            var item = list.Items.Add();
            item["Company"] = _id;
            item["IOTopic"] = topicId;
            item.Update();
            list.Update();
        }*/

        private IList<IOTopicDto> GetSelectedTopics()
        {
            var topics = new List<IOTopicDto>();
            foreach (RepeaterItem level1Item in IOLevel1Repeater.Items)
            {
                var level2Repeater = (Repeater)level1Item.FindControl("IOLevel2Repeater");
                if (level2Repeater == null)
                {
                    continue;
                }

                foreach (RepeaterItem level2Item in level2Repeater.Items)
                {
                    var topicRepeater = (Repeater)level2Item.FindControl("IOTopicRepeater");
                    if (topicRepeater == null)
                        continue;

                    foreach (RepeaterItem topicItem in topicRepeater.Items)
                    {
                        var check = (CheckBox)topicItem.FindControl("IOTopicCheckBox");
                        if (check.Checked)
                        {
                            var dto = new IOTopicDto();
                            dto.Id = int.Parse(check.InputAttributes["value"]);
                            dto.Title = check.Text;
                            topics.Add(dto);
                        }
                    }
                }
            }
            return topics.ToArray();
        }

        private string GetFileName()
        {
            var replacements = new Dictionary<string, string>
                                   {
                                       {"õ", "o"},
                                       {"ä", "a"},
                                       {"ö", "o"},
                                       {"ü", "u"},
                                       {"Õ", "o"},
                                       {"Ä", "a"},
                                       {"Ö", "o"},
                                       {"Ü", "u"},
                                       {" ", "-"}
                                   };

            var pageName = nameField.Text;
            foreach (var s in replacements.Keys)
                pageName = pageName.Replace(s, replacements[s]);
            pageName += ".aspx";
            return pageName;
        }

        private string GetWebUrl(SPSite site, string webUrl)
        {
            webUrl = webUrl.Replace(site.Url, string.Empty);
            if (!webUrl.StartsWith("/"))
                webUrl = "/" + webUrl;
            return webUrl;
        }
    }
}
